import React from 'react';
import codePush, { RemotePackage } from 'react-native-code-push';
import PortraitAlert from '../components/Alert/PortraitAlert';

import UpdateProgress from '../components/UpdateProgress';
import { CODE_PUSH_KEY } from '../constant';
import { modalOpen } from './global';

export const downLoadPackage = (update: RemotePackage): void => {
  modalOpen({
    Type: (): React.ReactElement => (
      <UpdateProgress
        update={update}
        packageSize={update.packageSize}
        download={(): void => downLoadPackage(update)}
      />
    ),
    needBack: true
  });
};

export const packageUpdate = (update: RemotePackage): void => {
  modalOpen({
    Type: (): React.ReactElement => (
      <PortraitAlert
        title="发现新版本"
        sureDesc="立即更新"
        subTitle={`抱歉您使用的版本太旧了，已无法继续使用，请立即更新版本，更新包大小共计${(
          update.packageSize /
          1024 /
          1024
        ).toFixed(2)}MB`}
        sureAction={(): void => {
          downLoadPackage(update);
        }}
      />
    ),
    needBack: true
  });
};

export const checkUpdate = (): void => {
  const syncOptions = {
    installMode: codePush.InstallMode.ON_NEXT_RESTART,
    mandatoryInstallMode: codePush.InstallMode.ON_NEXT_RESTART,
    deploymentKey: CODE_PUSH_KEY
  };
  codePush.sync(syncOptions);
};

export const checkForUpdate = (): Promise<any> => {
  return new Promise((resolve, reject): void => {
    const checkTimer = setTimeout((): void => {
      reject();
    }, 10 * 1000);

    codePush
      .checkForUpdate(CODE_PUSH_KEY)
      .then((update: RemotePackage | null): void => {
        clearTimeout(checkTimer);
        if (update) {
          resolve(update);
        } else {
          reject();
        }
      })
      .catch((): void => {
        clearTimeout(checkTimer);
        reject();
      });
  });
};

export const codePushUpdate = (): void => {
  codePush
    .checkForUpdate(CODE_PUSH_KEY)
    .then((update: RemotePackage | null): void => {
      if (update && update.isMandatory) {
        packageUpdate(update);
      } else {
        checkUpdate();
      }
    });
};
